const { ipcMain, BrowserWindow } = require('electron')
const path = require('path')
const WinState = require('electron-win-state').default
const saveImg = require('./saveImg')
const cssText = `width:60px; height:30px; background-color: cornflowerblue; border-radius: 5px; text-align :center; line-height:30px; position:fixed; bottom: 50px; right: 20px; z-index:1000; color: #fff; cursor:pointer;`
const js = `
   const div =document.createElement('div')
   div.innerHTML = '关闭窗口'
   div.addEventListener('click',()=>{myApi.close()})
   div.style.cssText = '${cssText}'
   document.body.appendChild(div)
`

let win = null

ipcMain.handle('on-open-event', (e, url) => {
  // 记录窗口状态
  const winState = new WinState({
    defaultWidth: 1200,
    defaultHeight: 800,
    electronStoreOptions: {
      name: 'window-state-open'
    }
  })
  // 创建新窗口
  win = new BrowserWindow({
    ...winState.winOptions,
    show: false,
    webPreferences: {
      preload: path.join(__dirname, '../preload/open.js')
    }
  })

  win.once('ready-to-show', () => {
    win.show()
  })

  win.loadURL(url)

  // 记录窗口状态
  winState.manage(win)

  // win.webContents.openDevTools()

  // 执行JavaScript(注入新窗口)
  win.webContents.executeJavaScript(js).catch()

  win.webContents.on('context-menu', (e, args) => {
    saveImg(args.srcURL)
  })
})

ipcMain.handle('on-close-event', () => {
  win.close()
})
